//
// Created by Administrator on 2025/9/13.
//

#include "system_api.h"
#include "sqlist.h"
#include "lwip_demo.h"
#include "rtc.h"
system_info_t system_info;

extern SeqList_t g_sensor_registry;
void sys_get_time(struct tm * time)
{
    static xSemaphoreHandle rtc_mutex=NULL;
    if (rtc_mutex==NULL)
    {
        rtc_mutex=xSemaphoreCreateMutex();
        while (rtc_mutex==NULL);
    }
    xSemaphoreTake(rtc_mutex,portMAX_DELAY);
    static RTC_DateTypeDef rdate;
    static RTC_TimeTypeDef rtime;
    HAL_RTC_GetTime(&hrtc,&rtime,RTC_FORMAT_BIN);
    HAL_RTC_GetDate(&hrtc,&rdate,RTC_FORMAT_BIN);
    time->tm_year=rdate.Year+100;
    time->tm_mon=rdate.Month-1;
    time->tm_mday=rdate.Date;
    time->tm_hour=rtime.Hours;
    time->tm_min=rtime.Minutes;
    time->tm_sec=rtime.Seconds;
    xSemaphoreGive(rtc_mutex);
}

void sys_set_time(struct tm * time)
{
    RTC_DateTypeDef rdate={0};
    rdate.Date=time->tm_mday;
    rdate.Month=time->tm_mon+1;
    rdate.Year=time->tm_year-100;
    rdate.WeekDay=time->tm_wday;

    RTC_TimeTypeDef rtime={0};
    rtime.Hours=time->tm_hour;
    rtime.Minutes=time->tm_min;
    rtime.Seconds=time->tm_sec;
    HAL_RTC_SetDate(&hrtc,&rdate,RTC_FORMAT_BIN);
    HAL_RTC_SetTime(&hrtc,&rtime,RTC_FORMAT_BIN);
    // system_info.timestamp=*time;
}

void sys_set_eth_status(bool status)
{
    system_info.network_status.eth_status=status;
}

bool sys_get_eth_status(void)
{
    return system_info.network_status.eth_status;
}

void sys_set_ble_status(bool status)
{
    system_info.network_status.ble_status=status;
}

bool sys_get_ble_status(void)
{
    return system_info.network_status.ble_status;
}

void sys_set_wifi_status(bool status)
{
    system_info.network_status.wifi_status=status;
}

bool sys_get_wifi_status(void)
{
    return system_info.network_status.wifi_status;
}

bool sys_get_ntp_status(void)
{
    return system_info.ntp_status;
}

void sys_set_ntp_status(bool status)
{
    system_info.ntp_status=status;
}
// void vApplicationTickHook(void)
// {
//     static size_t tick_count=0;
//     tick_count++;
//     tick_count%=1000;
//     if (tick_count==0)
//     {
//         system_info.timestamp++;
//         gmtime_r(&system_info.timestamp, &system_info.time);
//     }
// }

// void sys_get_time_struct(struct tm *time)
// {
//     memcpy(time, &system_info.time, sizeof(struct tm));
// }

void sys_info_daemon(void * pvParameters)
{
    UNUSED(pvParameters);
    snprintf(system_info.model,sizeof(system_info.model),"IOT_GW_19Y");
    snprintf(system_info.version,sizeof(system_info.version),"1.0.0");
    // while (system_info.time.tm_year==0);
    // strftime(system_info.uptime,sizeof(system_info.uptime),"%Y-%m-%d %H:%M:%S",&system_info.time);
    for (;;)
    {
        //SeqList_Get_Size(&g_sensor_registry,&system_info.sensor_num);
        vTaskDelay(3000);
    }
}
